package io.github.kouleen.minecraft.plugin.redpacket.listener;

import io.github.kouleen.minecraft.core.lang.annotation.MinecraftPluginAutoInject;
import io.github.kouleen.minecraft.core.lang.annotation.MinecraftPluginListener;
import io.github.kouleen.minecraft.plugin.redpacket.entity.RedPacket;
import io.github.kouleen.minecraft.plugin.redpacket.manager.RedPacketManager;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * @author zhangqing
 * @since 2025/10/3 23:59
 */
@MinecraftPluginListener
public class PlayerJoinListener implements Listener {

    @MinecraftPluginAutoInject
    private RedPacketManager redPacketManager;

    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event) {
        Player player = event.getPlayer();
        // 玩家加入时检查是否有未领取的红包
        Map<String, RedPacket> activeRedPackets = redPacketManager.getActiveRedPackets();
        for (RedPacket redPacket : activeRedPackets.values()) {
            Set<UUID> claimedPlayers = redPacket.getClaimedPlayers();
            // 红包未过期并且未领取
            if (!redPacket.isExpired() && !claimedPlayers.contains(player.getUniqueId())) {
                TextComponent textComponent = redPacketManager.handleRedPacketMessage(redPacket);
                player.spigot().sendMessage(textComponent);
                player.playSound(player.getLocation(), Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 1.0f, 1.0f);
            }
        }
    }
}